package jpg1980.gttunes.dao;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

public class DataSourceServiceLocator
{
	public static final DataSourceServiceLocator	INSTANCE		= new DataSourceServiceLocator();
	private DataSource						dataSource;
	private static final String				DATASOURCE_NAME	= "jdbc/gtdb";

	private DataSourceServiceLocator()
	{
		this.dataSource = lookupDataSource();
	}

	private DataSource lookupDataSource() throws RuntimeException
	{
		DataSource dataSource = null;
		try
		{
			Context env = (Context) new InitialContext().lookup("java:comp/env");

			dataSource = (DataSource) env.lookup(DATASOURCE_NAME);

			if (dataSource == null)
				throw new RuntimeException("`" + DATASOURCE_NAME + "' is an unknown DataSource");

		}
		catch (NamingException e)
		{
			throw new RuntimeException("Error resolving datasource: ", e);
		}
		return dataSource;
	}

	public DataSource getDataSource()
	{
		return this.dataSource;
	}
}
